package cn.com.jrj.base;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.Assert;

public class VnetAppContext {
	public static final int FROM_WEB = 0;
	public static final int FROM_APPLICATION = 1;

	private static final String KEY_INIT_FROM = "KEY_INIT_FROM";
	private static final String KEY_SPRING_CTX = "KEY_SPRING_CTX";
	private static final String KEY_TASK_EXECUTOR = "KEY_TASK_EXECUTOR";
	/* 
	 * 程序执行的上下文
	 */
	private static final Map<String, Object> context = new HashMap<String, Object>();

	public static void put(String k, Object v) {
		Assert.notNull(k);
		context.put(k, v);
	}

	public static void clear() {
		context.clear();
	}

	public static void configure(int from) {
		Assert.isTrue((from == FROM_WEB) || (from == FROM_APPLICATION));
		ApplicationContext ctx = null;
		if (from == FROM_WEB) {
			ctx = new ClassPathXmlApplicationContext("classpath:spring/spring_web.xml");
		} else {
			ctx = new ClassPathXmlApplicationContext("classpath:spring/spring_app.xml");
		}
		put(KEY_INIT_FROM, from);
		put(KEY_SPRING_CTX, ctx);
		put(KEY_TASK_EXECUTOR, (ThreadPoolTaskExecutor) ctx.getBean("taskExecutor"));
	}

	public static ApplicationContext getSpringCtx() {
		Object ctx = context.get(KEY_SPRING_CTX);
		Assert.isAssignable(ApplicationContext.class, ctx.getClass());
		return (ApplicationContext) ctx;
	}

	public static ThreadPoolTaskExecutor getTaskExecutor() {
		ApplicationContext ctx = getSpringCtx();
		Object o = ctx.getBean("taskExecutor");
		Assert.isAssignable(ThreadPoolTaskExecutor.class, o.getClass());
		return (ThreadPoolTaskExecutor) o;
	}

	public static boolean isInitFromWeb() {
		Integer from = (Integer) context.get(KEY_INIT_FROM);
		Assert.notNull(from);
		return from.intValue() == FROM_WEB;
	}

	public static boolean isInitFromApp() {
		Integer from = (Integer) context.get(KEY_INIT_FROM);
		Assert.notNull(from);
		return from.intValue() == FROM_APPLICATION;
	}
}
